package com.github.niefy.modules.wx.service.impl;

import com.github.niefy.modules.wx.result.WxMpDraftUploadResult;
import com.github.niefy.modules.wx.service.WxDraftService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.draft.WxMpAddDraft;
import me.chanjar.weixin.mp.bean.draft.WxMpDraftArticles;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

@Service
@CacheConfig(cacheNames = {"wxDraftServiceCache"})
@Slf4j
public class WxDraftServiceImpl implements WxDraftService {
    @Autowired
    WxMpService wxMpService;

    @Override
    @CacheEvict(allEntries = true)
    public WxMpDraftUploadResult draftUpload(String appid, WxMpDraftArticles article) throws WxErrorException {
        List<WxMpDraftArticles> articles = new ArrayList<>();
        articles.add(article);
        Assert.notEmpty(articles,"图文列表不得为空");
        log.info("上传图文素材到草稿箱...");
        wxMpService.switchoverTo(appid);
        WxMpAddDraft draft = new WxMpAddDraft();
        draft.setArticles(articles);
        return new WxMpDraftUploadResult(wxMpService.getDraftService().addDraft(draft));
    }

    @Override
    @CacheEvict(allEntries = true)
    public String submit(String mediaId) throws WxErrorException {
        log.info("发布图文素材");
        return wxMpService.getFreePublishService().submit(mediaId);
    }

    @Override
    @CacheEvict(allEntries = true)
    public WxMpFreePublishStatus getPushStatus(String publishId) throws WxErrorException {
//        return wxMpService.getFreePublishService().getPushStatus(publishId);
        WxMpFreePublishStatus result = wxMpService.getFreePublishService().getPushStatus(publishId);
        if (result!= null) {
            log.debug("publish_id: {}", result.getPublish_id());
            log.debug("publish_status: {}", result.getPublish_status());
            log.debug("article_id: {}", result.getArticle_id());
            log.debug("article_detail: {}", result.getArticle_detail());
            log.debug("fail_idx: {}", result.getFail_idx());
        }
        return result;

    }

}
